package mnnu.ghbe.controller;

import mnnu.ghbe.dto.Result;
import mnnu.ghbe.entity.User;
import mnnu.ghbe.service.UserService;
import mnnu.ghbe.util.JwtUtil;
import mnnu.ghbe.util.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private WechatUtil wechatUtil;
    
    @GetMapping("/login")
    public Result<Map<String, Object>> wechatLogin(@RequestParam String code) {
        try {
            // 调用微信接口获取openid
            String openid = wechatUtil.getOpenid(code);
            
            // 查找现有用户或创建新用户
            Optional<User> existingUser = userService.getUserByOpenid(openid);
            User user;
            if (existingUser.isPresent()) {
                // 如果用户已存在，使用现有用户信息
                user = existingUser.get();
            } else {
                // 如果是新用户，创建用户但保留空的昵称和头像
                user = new User(openid, "", "");
            }
            User savedUser = userService.saveOrUpdateUser(user);
            
            // 生成JWT Token
            String token = jwtUtil.generateToken(savedUser.getId());
            
            // 构造返回数据
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("user", savedUser);
            responseData.put("token", token);
            
            return new Result<>(200, "success", responseData);
        } catch (Exception e) {
            return Result.error(500, "微信登录失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/info")
    public Result<User> updateUserInfo(@RequestHeader("Authorization") String token,
                                       @RequestBody UserInfoRequest userInfoRequest) {
        try {
            // 从JWT token中提取用户ID
            String jwtToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(jwtToken);
            
            if (userId == null) {
                return Result.error(401, "无效的token");
            }
            
            // 查找用户
            Optional<User> userOptional = userService.getUserById(userId);
            if (!userOptional.isPresent()) {
                return Result.error(404, "用户不存在");
            }
            
            // 更新用户信息
            User user = userOptional.get();
            user.setAvatar(userInfoRequest.getAvatar());
            user.setNickname(userInfoRequest.getNickname());
            User updatedUser = userService.saveOrUpdateUser(user);
            
            return Result.success(updatedUser);
        } catch (Exception e) {
            return Result.error(500, "更新用户信息失败: " + e.getMessage());
        }
    }
    
    // 内部类用于接收用户信息更新请求
    public static class UserInfoRequest {
        private String nickname;
        private String avatar;
        
        public String getNickname() {
            return nickname;
        }
        
        public void setNickname(String nickname) {
            this.nickname = nickname;
        }
        
        public String getAvatar() {
            return avatar;
        }
        
        public void setAvatar(String avatar) {
            this.avatar = avatar;
        }
    }
}